package com.ljt.yupictureddd.interfaces.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ljt.yupictureddd.infrastracture.annotation.AuthCheck;
import com.ljt.yupictureddd.infrastracture.api.aliyunai.AliYunAiApi;
import com.ljt.yupictureddd.infrastracture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ljt.yupictureddd.infrastracture.api.imagesearch.SoImageSearchApiFacade;
import com.ljt.yupictureddd.infrastracture.api.imagesearch.model.SoImageSearchResult;
import com.ljt.yupictureddd.infrastracture.common.BaseResponse;
import com.ljt.yupictureddd.infrastracture.common.DeleteRequest;
import com.ljt.yupictureddd.infrastracture.common.ResultUtils;
import com.ljt.yupictureddd.domain.user.constant.UserConstant;
import com.ljt.yupictureddd.infrastracture.exception.ErrorCode;
import com.ljt.yupictureddd.infrastracture.exception.ThrowUtils;
import com.ljt.yupictureddd.shared.manager.auth.SpaceUserAuthManager;
import com.ljt.yupictureddd.shared.manager.auth.StpKit;
import com.ljt.yupictureddd.shared.manager.auth.annotaion.SaSpaceCheckPermission;
import com.ljt.yupictureddd.shared.manager.auth.model.SpaceUserPermissionConstant;
import com.ljt.yupictureddd.domain.picture.entity.Picture;
import com.ljt.yupictureddd.domain.space.entity.Space;
import com.ljt.yupictureddd.domain.user.entity.User;
import com.ljt.yupictureddd.domain.picture.valueobject.PictureReviewStatusEnums;
import com.ljt.yupictureddd.interfaces.assembler.PictureAssembler;
import com.ljt.yupictureddd.interfaces.vo.picture.PictureTagCategory;
import com.ljt.yupictureddd.interfaces.vo.picture.PictureVO;
import com.ljt.yupictureddd.application.service.PictureApplicationService;
import com.ljt.yupictureddd.application.service.SpaceApplicationService;
import com.ljt.yupictureddd.application.service.UserApplicationService;
import com.ljt.yupictureddd.interfaces.dto.picture.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
public class PictureController {
    @Resource
    UserApplicationService userApplicationService;

    @Resource
    PictureApplicationService pictureApplicationService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .maximumSize(10_000L)// 最大10000条
            .expireAfterWrite(Duration.ofMinutes(5))// 缓存五分钟过期
            .build();
    @Resource
    private SpaceApplicationService spaceApplicationService;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 图片上传接口
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                      PictureUploadRequest pictureUploadRequest,
                                      HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        PictureVO vo = pictureApplicationService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(vo);
    }

    /**
     * 图片上传接口
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse uploadPicture(@RequestBody PictureUploadRequest pictureUploadRequest,
                                      HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        String url = pictureUploadRequest.getUrl();
        PictureVO vo = pictureApplicationService.uploadPicture(url, pictureUploadRequest, loginUser);
        return ResultUtils.success(vo);
    }

    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR);

        User loginUser = userApplicationService.getLoginUser(request);
//        校验数据库有没有这条数据
        pictureApplicationService.deletePicture(id, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 只有管理员可用， 更新图片
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
//        1.校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(pictureUpdateRequest), ErrorCode.PARAMS_ERROR, "参数为空");
//        封装po后还是要校验
        Picture picture = PictureAssembler.toPictureEntity(pictureUpdateRequest);
        picture.validPicture();
//        更新判断存在
        Picture oldPicture = pictureApplicationService.getById(picture.getId());
        ThrowUtils.throwIf(ObjUtil.isNull(oldPicture), ErrorCode.NOT_FOUND_ERROR);
//        2.校验身份是不是管理员 =》 注解做了

        //        补充审核参数
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.fillReviewParams(picture, loginUser);
//        4.操作数据库
        boolean save = pictureApplicationService.updateById(picture);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 仅管理员可用的，根据id获取图片
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse getPictureById(long id, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(id < 0, ErrorCode.PARAMS_ERROR);
//        校验权限 =》 注解做了
//        校验数据库存在？
        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(oldPicture), ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(oldPicture);
    }

    /**
     * 根据id获取图片 （要脱敏）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse listPictureByPage(long id, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(id < 0, ErrorCode.PARAMS_ERROR);
//        校验数据库存在？

        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(oldPicture), ErrorCode.NOT_FOUND_ERROR);
//        校验权限
        if (oldPicture.getSpaceId() != null) {
            // 只有私有空间才需要校验权限. 公共图库的图片看到就看到呗
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission,ErrorCode.NO_AUTH_ERROR);
            // User loginUser = userService.getLoginUser(request);
            // pictureService.checkPictureAuth(oldPicture, loginUser);
        }
//        1.进行数据脱敏
        PictureVO pictureVO = PictureVO.getPictureVO(oldPicture, request);
        Space space = spaceApplicationService.getById(oldPicture.getSpaceId());
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取列表(管理员才可以用)
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureQueryRequest), ErrorCode.PARAMS_ERROR, "参数为空");
//        校验权限 = > 无需
//        校验数据库存在？ => 无需
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, pageSize), pictureApplicationService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取列表(封装类,脱敏类)
     */
    @PostMapping("/list/page/vo")
    public BaseResponse listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureQueryRequest), ErrorCode.PARAMS_ERROR, "参数为空");
//        校验权限 = > 无需
//        校验数据库存在？ => 无需
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 如果是私有空间,不用动
        if (spaceId == null) {
//        !!!  普通用户应该只能看到审核通过的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());
            // 如果是要查公共空间,这个字段要设置
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 如果是私有空间
            // User loginUser = userService.getLoginUser(request);
            // Space space = spaceService.getById(spaceId);
            // // 空间在数据库中不存在,抛出异常
            // ThrowUtils.throwIf(ObjUtil.isNull(space), ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // // 查的不是自己的空间,抛出异常
            // ThrowUtils.throwIf(ObjUtil.notEqual(space.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            // 已经改成权限注解校验 ⬇
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission,ErrorCode.NO_AUTH_ERROR);
        }
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, pageSize), pictureApplicationService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOList = pictureApplicationService.getPictureVOList(picturePage, request);
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 分页获取列表(封装类,脱敏类)（有缓存）
     */
    @PostMapping("/list/page/vo/cached")
    @Deprecated
    public BaseResponse listPictureVOByPageCached(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureQueryRequest), ErrorCode.PARAMS_ERROR, "参数为空");
//        校验权限 = > 无需
//        校验数据库存在？ => 无需
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
//        !!!  普通用户应该只能看到审核通过的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());

        // 这里查询缓存（redis或者caffeine）
        // 查询的准备工作
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String conditionStr = JSONUtil.toJsonStr(pictureQueryRequest);
        // 让这个conditionStr更加精简，使用摘要（哈希技术）
        String hashCondition = DigestUtil.md5Hex(conditionStr.getBytes());
        String redisKey = String.format("yu-picture:listPictureVOByPageCached:%s", hashCondition);
        String cacheKey = redisKey;// 这里就认为redisKey 和 本地缓存key一样

        // 1.查询本地缓存
        String result = LOCAL_CACHE.getIfPresent(redisKey);

        // 如果查询成功了,直接返回啦
        if (StrUtil.isNotBlank(result)) {
            Page<PictureVO> bean = JSONUtil.toBean(result, Page.class);
            return ResultUtils.success(bean);
        }

        // 2.查询redis缓存
        String redisResult = opsForValue.get(redisKey);

        // 如果查询redis成功了,要更新本地缓存
        if (StrUtil.isNotBlank(redisResult)) {
            Page<PictureVO> bean = JSONUtil.toBean(redisResult, Page.class);
            // 这里写入本地缓存
            LOCAL_CACHE.put(cacheKey, redisResult);
            return ResultUtils.success(bean);
        }


        // 3.缓存都查不到，只能查询数据库(代码能走到这里就说明查询缓存失败啦,缓存为空)
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, pageSize), pictureApplicationService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOList = pictureApplicationService.getPictureVOList(picturePage, request);

        String jsonStr = JSONUtil.toJsonStr(pictureVOList);
        // 对于redis，这里写入缓存,要设置时间,但是不要缓存雪崩(同时所有的缓存都没有了)
        // 设置缓存的过期时间,5 - 10 分钟过期,防止缓存雪崩
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        opsForValue.set(redisKey, jsonStr, cacheExpireTime, TimeUnit.SECONDS);

        // 这里写入本地缓存
        LOCAL_CACHE.put(cacheKey, jsonStr);

        return ResultUtils.success(pictureVOList);
    }

    /**
     * 编辑图片(给用户使用的)
     */
    @PostMapping("edit")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureEditRequest), ErrorCode.PARAMS_ERROR, "参数为空");
//        校验权限 = > 只有本人,或者管理员才行
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 审核图片
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse reviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureReviewRequest), ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量抓取并上传图片
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse batchUploadPicture(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request) {
//        校验参数（无）、转换为po再校验
        ThrowUtils.throwIf(ObjUtil.isNull(pictureUploadByBatchRequest), ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        Integer uploadCount = pictureApplicationService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }


    /**
     * 高性价比的一个返回接口，首页需要一个接口返回分类，这里直接写死，不写成动态的。（我觉得在项目快速上线的时候非常有性价比）
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse listPictureTagCategory() {
//        但是如果需要去
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest,
                                               HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(Objects.isNull(searchPictureByPictureRequest),ErrorCode.PARAMS_ERROR,"参数为空");
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId < 0 || pictureId == null , ErrorCode.PARAMS_ERROR,"图片id错误");
        // 校验权限 -> 无需
        // 校验存在
        Picture oldPicture = pictureApplicationService.getById(pictureId);
        ThrowUtils.throwIf(ObjUtil.isNull(oldPicture),ErrorCode.NOT_FOUND_ERROR,"不存在图片");
        // 调用自己在api包下写的以图搜图接口
        List<SoImageSearchResult> soImageSearchResultList = SoImageSearchApiFacade.searchImage(oldPicture.getUrl(), 0);
        return ResultUtils.success(soImageSearchResultList);
    }
    /**
     * 根据颜色主色调搜索
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(searchPictureByColorRequest),ErrorCode.PARAMS_ERROR,"参数为空");
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userApplicationService.getLoginUser(request);
        List<PictureVO> pictureVOList = pictureApplicationService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 批量编辑图片
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest,HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(pictureEditByBatchRequest),ErrorCode.PARAMS_ERROR,"参数为空");
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.editPictureByBatch(pictureEditByBatchRequest,loginUser);
        return ResultUtils.success(true);
    }
    /**
     * 创建AI扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(createPictureOutPaintingTaskRequest),ErrorCode.PARAMS_ERROR,"参数为空");
        ThrowUtils.throwIf(ObjUtil.isNull(createPictureOutPaintingTaskRequest.getPictureId()),ErrorCode.PARAMS_ERROR,"参数为空");
        User loginUser = userApplicationService.getLoginUser(request);
        CreateOutPaintingTaskResponse outPaintingTask = pictureApplicationService.createOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(outPaintingTask);
    }

    /**
     * 查询ai扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse getPictureOutPaintingTask(String taskId) {
        // 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(taskId),ErrorCode.PARAMS_ERROR,"参数为空");
        return ResultUtils.success(aliYunAiApi.getOutPaintingTaskResponse(taskId));
    }

}
